<!-- 修改密码 -->

<script setup>
import { ref } from "vue";
import { updatePassword } from "@/api/userCenter.js";

// 定义表单引用
const ruleFormRef = ref(null);

// 定义表单数据
const userData = ref({
  old_pwd: "",
  new_pwd: "",
  re_pwd: "",
});

// 自定义验证规则
// 新密码不能与原密码相同
const validatePwd = (rule, value, callback) => {
  if (value === userData.value.old_pwd) {
    callback(new Error("新密码不能与原密码相同！"));
  } else {
    callback();
  }
};
// 确认密码必须与新密码一致
const validateConfirmPwd = (rule, value, callback) => {
  if (value !== userData.value.new_pwd) {
    callback(new Error("两次输入的密码不一致！"));
  } else {
    callback();
  }
};

// 表单验证规则
const rules = {
  old_pwd: [
    { required: true, message: "请输入旧密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
  ],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
    { validator: validatePwd, trigger: "blur" },
  ],
  re_pwd: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    {
      pattern: /^\S{6,15}$/,
      message: "密码必须是6-15位的非空字符",
      trigger: "blur",
    },
    { validator: validateConfirmPwd, trigger: "blur" }, // 指定触发方式
  ],
};

// 提交修改
const onSubmit = async () => {
  // 校验表单
  ruleFormRef.value.validate();

  const res = await updatePassword({
    oldPassword: userData.value.old_pwd,
    newPassword: userData.value.new_pwd,
  });
  ElMessage({
    message: "修改成功",
    type: "success",
    plain: true,
  });
  // 清空表单数据
  ruleFormRef.value.resetFields();
};

// 重置表单
const onCancel = () => {
  ruleFormRef.value.resetFields();
};
</script>

<template>
  <Card title="修改密码">
    <!-- 默认插槽--内容 -->
    <el-form
      ref="ruleFormRef"
      style="max-width: 400px"
      :model="userData"
      :rules="rules"
      label-width="120px"
    >
      <el-form-item label="旧密码" prop="old_pwd">
        <el-input v-model="userData.old_pwd" type="password" />
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input v-model="userData.new_pwd" type="password" />
      </el-form-item>
      <el-form-item label="再次输入密码" prop="re_pwd">
        <el-input v-model="userData.re_pwd" type="password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
        <el-button @click="onCancel">重置</el-button>
      </el-form-item>
    </el-form>
  </Card>
</template>

<style lang="scss" scoped></style>
